package com.hui.qiniucloud.mapper;

import com.hui.qiniucloud.entity.ChatSession;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 聊天会话 Mapper 接口
 */
@Mapper
public interface ChatSessionMapper extends BaseMapper<ChatSession> {

    /**
     * 根据用户ID查询会话列表
     */
    @Select("SELECT * FROM chat_session WHERE user_id = #{userId} AND deleted = 0 ORDER BY updated_time DESC")
    List<ChatSession> selectByUserId(@Param("userId") Long userId);

    /**
     * 根据用户ID和角色ID查询会话列表
     */
    @Select("SELECT * FROM chat_session WHERE user_id = #{userId} AND character_id = #{characterId} AND deleted = 0 ORDER BY updated_time DESC")
    List<ChatSession> selectByUserIdAndCharacterId(@Param("userId") Long userId, @Param("characterId") String characterId);

    /**
     * 根据会话ID和用户ID查询会话（权限验证）
     */
    @Select("SELECT * FROM chat_session WHERE id = #{sessionId} AND user_id = #{userId} AND deleted = 0")
    ChatSession selectByIdAndUserId(@Param("sessionId") Long sessionId, @Param("userId") Long userId);

    /**
     * 更新会话的最后消息和消息数量
     */
    @Update("UPDATE chat_session SET last_message = #{lastMessage}, message_count = #{messageCount}, updated_time = NOW() WHERE id = #{sessionId} AND deleted = 0")
    int updateLastMessageAndCount(@Param("sessionId") Long sessionId, @Param("lastMessage") String lastMessage, @Param("messageCount") Integer messageCount);

    /**
     * 更新会话标题
     */
    @Update("UPDATE chat_session SET title = #{title}, updated_time = NOW() WHERE id = #{sessionId} AND user_id = #{userId} AND deleted = 0")
    int updateTitleByIdAndUserId(@Param("sessionId") Long sessionId, @Param("userId") Long userId, @Param("title") String title);

    /**
     * 根据关键词搜索用户的会话
     */
    @Select("SELECT * FROM chat_session WHERE user_id = #{userId} AND deleted = 0 AND (title LIKE CONCAT('%', #{keyword}, '%') OR last_message LIKE CONCAT('%', #{keyword}, '%')) ORDER BY updated_time DESC")
    List<ChatSession> searchByUserIdAndKeyword(@Param("userId") Long userId, @Param("keyword") String keyword);
}